package com.sophie.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class HTTP 
{
	public static final int ONLINE = 1;
	public static final int OFFLINE = 0;
	
	private URL url;
	private String data;
	private int state;
	
	public HTTP(String url)
	{
		try 
		{
			this.url = new URL(url);
			
			if(!ping())
			{
				state = HTTP.OFFLINE;
			}
			
			else
			{
				state = HTTP.ONLINE;
			}
		}
		
		catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void resetData()
	{
		this.data = new String();
	}
	
	private void addData(String variable,String value)
	{
		try 
		{
			if(data.length() > 0)
			{
				data += "&" + URLEncoder.encode(variable,"UTF-8") + "=" + URLEncoder.encode(value,"UTF-8");
			}
			
			else
			{
				data += URLEncoder.encode(variable,"UTF-8") + "=" + URLEncoder.encode(value,"UTF-8");
			}
		}
		
		catch (Exception e) 
		{
		}
	}
	
	private BufferedReader conect()
	{
		try
		{
			URLConnection connection = url.openConnection();
			connection.setDoOutput(true);
			
			OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
			writer.write(data);
			writer.flush();
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			
			return reader;
		}
		
		catch(Exception exception)
		{
			
		}
		
		return null;
	}
	
	private boolean ping()
	{
		boolean response = false;
		String line = "";
		int value=0;
		
		try
		{
			this.resetData();
			this.addData("base", "27012012");
			this.addData("action", "ping");
			
			BufferedReader reader = conect();
			
			while((line = reader.readLine()) != null)
			{
				if(line.compareTo("") != 0)
				{
					if(!line.contains("<"))
					{
						value = 1;
					}
				}
			}
		}
		
		catch(Exception exception)
		{}
		
		if(value == 1)
		{
			response = true;
		}
		
		return response;
	}

	public void login(String user,String password)
	{
		String line;
		
		if(state == HTTP.ONLINE)
		{
			try
			{
				resetData();
				addData("base","27012012");
				addData("action","login");
				addData("user",user);
				addData("pass",password);
				
				/* Debug Mode
				System.out.println(data);
				*/
				
				BufferedReader reader = conect();
				 
				while((line = reader.readLine()) != null)
				{
					System.out.println(line);
				}
			}
			
			catch(Exception e)
			{}
		}
	}
}
